package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
/**
 * 定时任务类，定时处理订单状态
 */
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    public static final String REASON = "订单超时，自动取消";
    /**
     * 处理订单超时的方法
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟触发一次
    @Transactional
    public void processTimeoutOrder() {
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime timeThreshold = currentTime.minusMinutes(15);

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, timeThreshold);
        for (Orders order : ordersList) {
            synchronized (this) {
                Orders currentOrder = orderMapper.getById(order.getId());
                if (currentOrder.getStatus().equals(Orders.PENDING_PAYMENT) && currentOrder.getOrderTime().isBefore(timeThreshold)) {
                    currentOrder.setStatus(Orders.CANCELLED);
                    currentOrder.setCancelReason(REASON);
                    currentOrder.setCancelTime(currentTime);
                    orderMapper.update(currentOrder);
                }
            }
        }
    }


    /**
     * 处理订单一直处于派送中的方法
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点触发一次
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        for(Orders orders : ordersList){
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }
    }

}
